package com.atguigu2.netty.simple;

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;


/**
 * @author sunfeng
 * @date 2021/03/29 10:05
 **/
@Slf4j
public class NioSocketClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NioSocketClientHandler());
                        }
                    });
            System.out.println("客户端ok");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();

            channelFuture.channel().closeFuture().sync();
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        log.info("监听端口成功");
                    }else{
                        log.error("监听端口失败");
                    }
                }
            });
        } finally {
            group.shutdownGracefully();
        }


    }
}
